package com.hzlx.config;

import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.SecurityWebFiltersOrder;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;


@Configuration
@EnableWebFluxSecurity//用于在响应式 Web 应用中启用 Spring Security 功能 。启用基于 WebFlux 的安全功能，如认证、授权等
public class SecurityConfig {
    @Resource
    AccessReactiveAuthorizationManager accessAuthorizationManager;
    @Resource
    LoginReactiveAuthenticationManager loginReactiveAuthenticationManager;
    @Resource
    TokenFilter tokenFilter;
    @Bean
    public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
        return http
                .csrf(csrf -> csrf.disable()) // 完全禁用 CSRF
        //        .authenticationManager(loginReactiveAuthenticationManager) //注册认证提供者
                // 放行所有请求，由JwtAuthFilter 控制权限
                .authorizeExchange(exchanges -> exchanges
                        .pathMatchers("/auth/login").permitAll()
                        .pathMatchers("/api/menus").permitAll()
                        .anyExchange()
                        .access(accessAuthorizationManager)
                )
                .addFilterAfter(corsFilter(),SecurityWebFiltersOrder.FIRST)
                .addFilterAfter(tokenFilter, SecurityWebFiltersOrder.AUTHENTICATION)
                .httpBasic().disable() // 关闭基本认证
                .formLogin().disable() // 关闭表单认证
                .build();
    }
    @Bean
    public CorsWebFilter corsFilter(){//这个方法是 Spring Security 配置中用于处理跨域资源共享 (CORS) 的过滤器配置。
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOrigin("http://localhost:5173");
        config.addAllowedMethod("*");
        config.addAllowedHeader("*");
        config.addExposedHeader("Authorization");
        config.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",config);
        return new CorsWebFilter(source);
    }
}
